<?php

namespace Portal\Domain;

class Dept
{
    public function getDeptName($deptId)
    {
        $cacheKey = 'Dept.getDeptName.'.$deptId;
        $cacheData = \PhalApi\DI()->cache->get($cacheKey);
        if ($cacheData !== null) {
            return $cacheData;
        }
        $data = \Portal\Model\Dept::notorm()->select('name')->where(['id' => $deptId])->fetchOne();
        $returnData = '';
        if (isset($data['name'])) {
            $returnData = $data['name'];
        }
        \PhalApi\DI()->cache->set($cacheKey, $returnData);
        return $returnData;
    }

    public function getDeptLevel($hasPermissionData)
    {
        $notorm = \Portal\Model\Dept::notorm();
        if ($hasPermissionData == "all") {
            $depts = $notorm->select('id AS value,id,name AS label,parent_id AS parentId')->where(['status' => 1,'is_deleted' => 0])->order('sort', 'id')->fetchAll();
        } elseif (is_array($hasPermissionData) && !empty($depts)) {
            //加权限验证
            $depts = $notorm->select('id AS value,id,name AS label,parent_id AS parentId')->where(['status' => 1,'is_deleted' => 0,'create_by' => $hasPermissionData])->order('sort', 'id')->fetchAll();
            // $depts = $notorm->select('id AS value,id,name AS label,parent_id AS parentId')->where(['status' => 1,'is_deleted' => 0])->order('sort', 'id')->fetchAll();
        }
        $depts = $this->formatDepts($depts);
        $deptInfo = $this->getChildDepts(0, $depts, ['id','parentId']);
        return $deptInfo;
    }

    protected function getByParentId(&$depts, $parentId = 0)
    {
        $needDepts = array();
        foreach ($depts as $key => $it) {
            if ($it['parent_id'] == $parentId) {
                $needDept['value'] = $it['id'];
                $needDept['label'] = $it['name'];
                $needDepts[] = $needDept;
                unset($depts[$key]);
            }
        }
        return $needDepts;
    }
    protected function addChildId($menu, $children)
    {
        $parentId = $menu['id'];
        $childrenArr = [];
        foreach ($children as $item) {
            if ($item['parent_id'] == $parentId) {
                $childrenArr[] = $item;
            }
        }
        if (!empty($childrenArr)) {
            $menu['children'] = $childrenArr;
        }

        return $menu;
    }

    public function getDeptList($where)
    {
        $notorm = \Portal\Model\Dept::notorm();
        if (empty($where)) {
            $depts = $notorm->select('id,name,parent_id AS parentId,code,sort,status,update_time')->where(['is_deleted' => 0])->order("sort", "id")->fetchAll();
        } else {
            $depts = $notorm->select('id,name,parent_id,sort,status,code,update_time')->where($where)->where(['is_deleted' => 0])->order("sort", "id")->fetchAll();
        }
        $depts = $this->formatDepts($depts);


        $deptInfo = $this->getChildDepts(0, $depts);
        return $deptInfo;
    }
    protected function getByParentIdList(&$depts, $parentId = 0)
    {
        $needDepts = array();
        foreach ($depts as $key => $it) {
            if ($it['parent_id'] == $parentId) {
                $needDept['id'] = $it['id'];
                $needDept['name'] = $it['name'];
                $needDept['parentId'] = $it['parent_id'];
                $needDept['parent_id'] = $it['parent_id'];
                $needDept['sort'] = $it['sort'];
                $needDept['status'] = $it['status'];
                $needDept['createTime'] = date('Y-m-d H:i:s', $it['create_time']);
                $needDept['updateTime'] = date('Y-m-d H:i:s', $it['update_time']);
                $needDepts[] = $needDept;
                unset($depts[$key]);
            }
        }
        return $needDepts;
    }
    //获取树等级
    public function getTreePath($parentId, &$treeArray = [])
    {
        $parentId = intval($parentId);
        // 在数组左边插入元素
        array_unshift($treeArray, $parentId);
        if (intval($parentId) > 0) {
            //获取上级父id
            $getParentData = \Portal\Model\Dept::notorm()->select('parent_id')->where(['id' => $parentId])->fetchOne();
            if (is_array($getParentData) && !empty($getParentData)) {
                $parentId = intval($getParentData['parent_id']);
                // array_unshift($treeArray, $parentId);
                $this->getTreePath($parentId, $treeArray);
            }
        }
        return  $treeArray;
    }
    //获取所有子级
    public function getChildren($id, &$childArray = [])
    {
        $currentChildArr = [];
        $getChildDatas = \Portal\Model\Dept::notorm()->select('id')->where(['parent_id' => $id])->fetchAll();
        if (is_array($getChildDatas) && !empty($getChildDatas)) {
            foreach ($getChildDatas as $getChildData) {
                $currentChildArr[] = $getChildData['id'];
                $childArray[] = $getChildData['id'];
            }
            //递归处理
            foreach ($currentChildArr as $currentId) {
                $this->getChildren($currentId, $childArray);
            }
        }

        return  $childArray;
    }
    //搜索菜单结果格式化

    /**
     """
    获取当前用户可以查看的用户ID范围

    :param data_scope: 数据权限级别
    :return: "all" 或 用户ID列表
    """
     */
    public function getViewableUserIds($currentUserId, $currentDeptId, $dataScope)
    {
        # 1. 所有数据权限
        if ($dataScope == "1") {
            return "all";
        }
        $allIds = [];
        # 2. 本部门及子部门数据权限
        if ($dataScope == "2") {
            # 获取当前用户部门及所有子部门
            $deptIds = array_merge([$currentDeptId], $this->getChildren($currentDeptId));
            $deptIds = array_unique($deptIds);
            # 获取这些部门的所有用户ID
            $adminDomain = new Admin();
            $allIds = $adminDomain->getDepartmentUserIds($deptIds);
            return $allIds;
        }
        #3.本部门数据
        if ($dataScope == "3") {
            # 获取当前用户部门及所有子部门
            $deptIds = array_merge([$currentDeptId]);
            # 获取这些部门的所有用户ID
            $adminDomain = new Admin();
            $allIds = $adminDomain->getDepartmentUserIds($deptIds);
            return $allIds;
        }
        # 4. 仅本人数据权限
        if ($dataScope == "4") {
            $allIds = [$currentUserId];
            return $allIds;
        }

    }

    /**
     *
     *
    验证当前用户是否有权限操作目标用户的数据

    :param current_user: 当前用户对象
    :param data_scope: 数据权限级别
    :param target_user_id: 被操作的用户ID
    :return: True或False
     */
    public function hasPermissionToOperation($currentUserId, $currentDeptId, $dataScope, $targetUserId)
    {
        # 如果目标用户就是当前用户，总是允许操作
        if ($currentUserId == $targetUserId) {
            return true;
        }
        # 1. 所有数据权限
        if ($dataScope == "1") {
            return true;
        }
        # 2. 本部门及子部门数据权限
        if ($dataScope == "2") {
            # 获取当前用户部门及所有子部门
            # 获取当前用户部门及所有子部门
            $deptIds = array_merge([$currentDeptId], $this->getChildren($currentDeptId));
            # 检查目标用户的部门是否在可访问的部门列表中
            # 获取这些部门的所有用户ID
            $adminModel = new \Portal\Model\Admin();

            $targetUserDeptData = $adminModel::notorm()->select('dept_id')->where(['id' => $targetUserId])->fetchOne();
            $targetUserDeptId = intval($targetUserDeptData['dept_id']);
            # 检查目标用户的部门是否在可访问的部门列表中
            return in_array($targetUserDeptId, $deptIds);
        }
        # 3. 本部门数据权限
        if ($dataScope == "3") {
            $adminModel = new \Portal\Model\Admin();
            $targetUserDeptData = $adminModel::notorm()->select('dept_id')->where(['id' => $targetUserId])->fetchOne();
            $targetUserDeptId = intval($targetUserDeptData['dept_id']);
            # 检查目标用户是否在同一部门
            return $currentDeptId == $targetUserDeptId;
        }
        # 4. 仅本人数据权限
        if ($dataScope == "4") {
            # 仅本人数据权限下，不能操作其他用户的数据
            return false;
        }

    }
    private function formatDepts($depts)
    {
        if (is_array($depts) && empty($depts)) {
            return $depts;
        }
        if (!is_array($depts)) {
            return [];
        }
        foreach ($depts as $key => $dept) {
            if (isset($dept['update_time'])) {
                $dept['update_time'] = date('Y-m-d H:i:s', $dept['update_time']);
            }
            if (isset($dept['id'])) {
                $dept['id'] = strval($dept['id']);
            }
            if (isset($dept['parentId'])) {
                $dept['parentId'] = strval($dept['parentId']);
            }
            if (isset($dept['value'])) {
                $dept['value'] = strval($dept['value']);
            }
            $depts[$key] = $dept;
        }
        return $depts;
    }
    private function getChildDepts($parentId, $allDepts, $deleteFields = [])
    {
        $childDepts = [];
        foreach ($allDepts as $dept) {
            if ($dept['parentId'] == $parentId) {
                $id = $dept['id'];
                $children = $this->getChildDepts($id, $allDepts);
                if ($children) {
                    $dept['children'] = $children;
                }
                $childDepts[] = $dept;
            }
        }
        return $childDepts;
    }
}
